package com.easyfun.healthmagicbox;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.easyfun.healthmagicbox.base.BaseActivity;
import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.comm.DoctorProfileDownloadTask;
import com.easyfun.healthmagicbox.comm.HealthInputDataDeleteTask;
import com.easyfun.healthmagicbox.comm.HealthThreadPool;
import com.easyfun.healthmagicbox.comm.PersonQuestionDeleteTask;
import com.easyfun.healthmagicbox.comm.PersonQuestionsDownloadTask;
import com.easyfun.healthmagicbox.comm.PersonQuestionsUploadTask;
import com.easyfun.healthmagicbox.inputviews.DoctorLinkActivity;
import com.easyfun.healthmagicbox.inputviews.DoctorSearchActivity;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.ServerResponseCode;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.DoctorAndSuggestion;
import com.easyfun.healthmagicbox.pojo.DoctorProfile;
import com.easyfun.healthmagicbox.pojo.HealthInputData;
import com.easyfun.healthmagicbox.pojo.PersonQuestion;
import com.easyfun.healthmagicbox.sync.BasicCommCallback;
import com.easyfun.healthmagicbox.widget.DialogBuilder;
import com.easyfun.healthmagicbox.widget.DialogBuilder.OnDialogButtonClickListener;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.easyfun.healthmagicbox.util.URIConverter;
import com.j256.ormlite.dao.Dao;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.drm.DrmStore.RightsStatus;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class SubDocoterSuggestionActivity extends BaseActivity implements DatabaseAccess{


	protected String m_personid;
    public Handler mHandler;
    private SparseIntArray inputlistIDs = new SparseIntArray();
    
	private static final String LOGTAG = SubDocoterSuggestionActivity.class.getSimpleName();

	protected String getPersonid() {
		return m_personid;
	}
	ListView listview;
	ListView questionlist;

	private ArrayAdapter<String> mQuestionList;

	/**
	 * this activity need the person ID
	 * 
	 * @return
	 */
	protected boolean checkPersonId() {
		m_personid = getIntent().getStringExtra(ConstantData.HMBPERSONID);
		//
		if ((m_personid == null) || (m_personid.length() == 0)) {
			setResult(RESULT_CANCELED);
			finish();
			return false;
		}
		return true;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.three);
		
		if (!checkPersonId())
			return;
		
		mHandler = new Handler() {  
	        @Override  
	        public void handleMessage(Message msg) {  
	            if(msg.what == ServerResponseCode.SUCCESS.toInteger()) {  
	                questionListRefresh();
	            } else if(msg.what == ServerResponseCode.NOMORE.toInteger()
	            		|| msg.what == ServerResponseCode.FAILED.toInteger()) {
	            	Log.d("Ping", "No need to update database" + msg.what + "\n");
	            	 questionListRefresh();
	            }else if(msg.what == ServerResponseCode.NOCONNECTION.toInteger()) {
	            	questionListRefresh();
	            }
	            super.handleMessage(msg);  
	        }  
	    };  
		MyAdapter adapter = new MyAdapter(this);

		// 绑定Layout里面的ListView
		listview = (ListView) findViewById(R.id.suggestionlist);
		// 添加并且显示
		listview.setAdapter(adapter);

		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				
				DialogBuilder builder = 
						new DialogBuilder(SubDocoterSuggestionActivity.this)
					.setTitle("医生介绍")//设置对话框标题
					.setCustomizedContent("赞一个","关闭",R.layout.dialog_item_doctor, 
							new OnDialogButtonClickListener() {
						
						@Override
						public void onDialogButtonClick(Context context, DialogBuilder builder,
								Dialog dialog, int dialogId, int which) {
							if (which == BUTTON_RIGHT)
							{
								dialog.dismiss();
							}
							
						}
					});
				TextView doctorname = (TextView) builder.getDialog().findViewById(R.id.diagDoctorName);
				TextView doctorhospital = (TextView) builder.getDialog().findViewById(R.id.diagDoctorHospital);
				TextView doctorIntro = (TextView) builder.getDialog().findViewById(R.id.diagDoctorIntroduction);
				String doctorID = (String) getData().get(position).get("doctorID");
				

				String doctorSex = (String) getData().get(position).get("doctorSex");
				String doctorAge = (String)getData().get(position).get("doctorAge");
				String doctorPicFile = (String)getData().get(position).get("doctorPicFile");
				String doctorName = (String)getData().get(position).get("doctorName");
				String doctorHospital = (String)getData().get(position).get("doctorHospital");
				String doctorDepartment = (String)getData().get(position).get("doctorDepartment");
				String doctorIntroduction = (String)getData().get(position).get("doctorIntroduction");
				String doctorShortIntro = (String)getData().get(position).get("doctorShortIntro");
				doctorname.setText(doctorName);
				doctorhospital.setText(doctorHospital+" "+doctorDepartment);
				doctorIntro.setText(doctorIntroduction);
				
				ImageView image = (ImageView) builder.getDialog().findViewById(R.id.doctorHeadPic);
				
				image.setImageBitmap(URIConverter.getDoctorHeadFromAppSDCard(
						SubDocoterSuggestionActivity.this,doctorPicFile,doctorSex
								));
//				if (doctorSex.equals("男"))
//				{
//					image.setImageResource( R.drawable.cartoondoc);						
//				}else
//				{
//					image.setImageResource( R.drawable.cartoondocfemale);					
//				}
				
				if (doctorID == null)
				{
					Log.e(LOGTAG, "doctor ID is null");
					return;
				}

				builder.create()
				.show();

			}
		});
		

		listview = (ListView) findViewById(R.id.suggestionlist);
		
		Button butSubmitQuestion = (Button) findViewById(R.id.butInputQuestion);
		butSubmitQuestion.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showDialog();
			}
		});
		
		questionlist = (ListView) findViewById(R.id.questionlist);

		 mQuestionList = new ArrayAdapter<String>(this,
				R.layout.common_list_item_without_indicator,
				R.id.item_text,new ArrayList<String>());

		 questionlist.setOnItemLongClickListener(new OnItemLongClickListener() {
				@Override
				public boolean onItemLongClick(AdapterView<?> parent, View view,
						int position, long id) {
					final Integer inputid = (int) inputlistIDs.get(position);
					if (mQuestionList.isEmpty() || inputid == 0)
						return false;
					
					new DialogBuilder(SubDocoterSuggestionActivity.this)
						.setTitle("是否删除")
						.setMessage(mQuestionList.getItem(position).toString())
						.setButtons("确定", "取消", new OnDialogButtonClickListener() {
							
							@Override
							public void onDialogButtonClick(Context context, DialogBuilder builder,
									Dialog dialog, int dialogId, int which) {
								if (which == BUTTON_LEFT)
								{
									try {
										Dao<PersonQuestion, Integer> inputdao = getHelper(SubDocoterSuggestionActivity.this).getQuestionsDao();
										PersonQuestion hid = inputdao.queryForId(inputid);
										inputdao.deleteById(inputid);
										getQuestions(mQuestionList);					
										mQuestionList.notifyDataSetChanged();
										
										PersonQuestionDeleteTask task = new
												PersonQuestionDeleteTask(hid.getSyncid().toString(),
														hid.getPersonID(),
														SubDocoterSuggestionActivity.this,
														new BasicCommCallback());
										HealthThreadPool.getInstance().execute(task);
										
									} catch (SQLException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
								else
								{
									dialog.dismiss();
								}
							}
						}).create().show();
					
					return true;
				}
			});
		int questions = getQuestions(mQuestionList);
		if(questions == 0) {
			Log.e(LOGTAG, "no question in db, ready to download it from server");
			PersonQuestionsDownloadTask task = new PersonQuestionsDownloadTask( 
					SubDocoterSuggestionActivity.this,
					getPersonid(), 
					new BasicCommCallback(mHandler));
			HealthThreadPool.getInstance().execute(task);
			mQuestionList.remove("没有数据");
			mQuestionList.add("下载中...");
		}
		mQuestionList.setNotifyOnChange(true);
		questionlist.setAdapter(mQuestionList);
		
//		Button butSearchDoc = (Button) findViewById(R.id.butSearchDoc);
//		butSearchDoc.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				final Intent intent = new Intent(
//						SubDocoterSuggestionActivity.this,
//						DoctorSearchActivity.class);
//				intent.putExtra(ConstantData.HMBPERSONID, m_personid);
//				SubDocoterSuggestionActivity.this.startActivity(intent);
//			}
//		});
		
	
	}
	//SparseArray<String> clickMap = new SparseArray<String>();
	
	private List<Map<String, Object>> getData() {
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();

		List<DoctorAndSuggestion> suggestions = null;
		try {
			Dao<DoctorAndSuggestion, Integer> suggestionDao = getHelper(this).getDoctorSuggestionDao();
			
			suggestions = 
					suggestionDao.queryBuilder().orderBy("suggestionTime", false).where().eq("personID", getPersonid()).query();
			
			for (DoctorAndSuggestion sug: suggestions)
			{

				Map<String,Object> map = new HashMap<String,Object>();
				map.put("title", sug.getSuggestion());
				Dao<DoctorProfile, Integer> doctorProfileDao = getHelper(this).getDoctorProfileDao();
				List<DoctorProfile> doctors = doctorProfileDao.queryBuilder().where().eq("doctorID", sug.getDoctorID()).query();
				if (doctors.size() == 1)
				{
					DoctorProfile dp = doctors.get(0);
					map.put("info", dp.getDoctorName() +" "+ dp.getDoctorHospital());
					//clickMap.append(i, dp.getDoctorID());
					map.put("doctorSex",dp.getDoctorSex());
					map.put("doctorAge", dp.getDoctorAge());
					map.put("doctorPicFile", dp.getDoctorPictureFile());
					map.put("doctorName",dp.getDoctorName());
					map.put("doctorHospital",dp.getDoctorHospital());
					map.put("doctorDepartment", dp.getDoctorDepartment());
					map.put("doctorIntroduction",dp.getDoctorIntroduction());
					map.put("doctorShortIntro",dp.getDoctorShortIntro());

					String docSex = (String) map.get("doctorAge");
					BitmapDrawable bmd = new BitmapDrawable(
							URIConverter.getDoctorHeadFromAppSDCard(
									SubDocoterSuggestionActivity.this, 
									dp.getDoctorPictureFile(), dp.getDoctorSex()));
					map.put("img",bmd);
//					if (docSex.equals("男"))
//					{
//						map.put("img", R.drawable.cartoondoc);						
//					}else
//					{
//						map.put("img", R.drawable.cartoondocfemale);					
//					}

				}
				else
				{
					Log.e(LOGTAG, "no doctor in db");
					DoctorProfileDownloadTask task = new DoctorProfileDownloadTask( 
							sug.getDoctorID(),
							SubDocoterSuggestionActivity.this, 
							new BasicCommCallback());
					HealthThreadPool.getInstance().execute(task);
					map.put("img", new BitmapDrawable(
							URIConverter.getDoctorHeadFromAppSDCard(
									SubDocoterSuggestionActivity.this, 
									"", "男")));	
				}
				map.put("doctorID",sug.getDoctorID());
				list.add(map);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}


	private int getQuestions(ArrayAdapter<String> mQuestionList2) {
		mQuestionList2.clear();
		
		List<PersonQuestion> questions = null;
		try {
			Dao<PersonQuestion, Integer> questionDao = getHelper(this).getQuestionsDao();
			
			questions = questionDao.queryBuilder().orderBy("questionTime", false).where().eq("personID", getPersonid()).query();
			int i = 0;
			if(questions.size() != 0) {
				for (PersonQuestion question: questions)
				{
					mQuestionList2.add(question.getQuestion());
					inputlistIDs.put(i, Integer.valueOf(question.getId()));
					i ++;
				}
			} else {//no questions data in db.
				mQuestionList2.add("没有数据");
				inputlistIDs.clear();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return questions.size();
	}
	
	private List<Map<String, Object>> getDemoData() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("title", "请您多运动吃些清淡的");
		map.put("info", "安贞医院 李大夫");
		map.put("img", R.drawable.one);
		list.add(map);

		map = new HashMap<String, Object>();
		map.put("title", "多去户外运动，少吃多餐");
		map.put("info", "协和医院 高大夫");
		map.put("img", R.drawable.two);
		list.add(map);

		map = new HashMap<String, Object>();
		map.put("title", "少吃油腻");
		map.put("info", "北大医院 田大夫");
		map.put("img", R.drawable.three);
		list.add(map);

		return list;
	}

	/**
	 * listview中点击按键弹出对话框
	 */
	public void showInfo() {

	}

	public final class ViewHolder {
		public ImageView img;
		public TextView title;
		public TextView info;
		public String doctorID;
		// public Button viewBtn;
	}

	public class MyAdapter extends BaseAdapter {

		private List<Map<String, Object>> mData;
		
		private LayoutInflater mInflater;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			mData = getData();
			return mData.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder = null;
			if (convertView == null) {

				holder = new ViewHolder();

				convertView = mInflater.inflate(R.layout.docoterlistitem, null);
				holder.img = (ImageView) convertView.findViewById(R.id.img);
				holder.title = (TextView) convertView.findViewById(R.id.title);
				holder.info = (TextView) convertView.findViewById(R.id.info);
				// holder.viewBtn =
				// (Button)convertView.findViewById(R.id.view_btn);
				convertView.setTag(holder);

			} else {

				holder = (ViewHolder) convertView.getTag();
			}

			holder.img.setBackgroundDrawable( (Drawable) mData.get(position).get(
					"img"));
			holder.title.setText((String) mData.get(position).get("title"));
			holder.info.setText((String) mData.get(position).get("info"));

			// holder.viewBtn.setOnClickListener(new View.OnClickListener() {
			//
			// @Override
			// public void onClick(View v) {
			// showInfo();
			// }
			// });

			return convertView;
		}

	}
	
	DatabaseHelper databaseHelper;
	/**
	 * You'll need this in your class to get the helper from the manager once per class.
	 */

	@Override
	public DatabaseHelper getHelper(Context context) {
		if (databaseHelper == null) {
			databaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);
		}
		return databaseHelper;
	}
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		
		super.onWindowFocusChanged(hasFocus);
		if (hasFocus)
		{
			questionListRefresh();
		}
	}

	
	@Override  
    public boolean onOptionsItemSelected(MenuItem item) {  
       
        return super.onOptionsItemSelected(item,this);  
    }  
	

	public void questionListRefresh() {
		listview.invalidateViews();
		getQuestions(mQuestionList);
		mQuestionList.notifyDataSetChanged();
	}
	public void showDialog(){
		final Context context = this;
		
		//创建对话框
		DialogBuilder dialogbuilder = new DialogBuilder(context)
		.setTitle("提问")//设置对话框标题
		.setCustomizedContent("提交","取消",R.layout.dialog_item_textinput, 
				new OnDialogButtonClickListener(){			
			@Override
			public void onDialogButtonClick(Context context,
					DialogBuilder builder, Dialog dialog, int dialogId,
					int which) {
				if (which == BUTTON_LEFT)
				{
					EditText edit = 
							(EditText) dialog.findViewById(R.id.dialogQuestion);
					addQuestion(edit.getText().toString());
				}
			}
		});
		EditText edit = 
				(EditText) dialogbuilder.getDialog().findViewById(R.id.dialogQuestion);
		edit.setLines(3);
		edit.setWidth(200);
		dialogbuilder.create().show();
	}
	
//	public void showDialog7(){
//		final Context context = this;
//		
//		//初始化自定义布局参数
//		LayoutInflater layoutInflater = getLayoutInflater();
//		//为了能在下面的OnClickListener中获取布局上组件的数据，必须定义为final类型.
//		final View customLayout = layoutInflater.inflate(R.layout.dialog_item_textinput, (ViewGroup)findViewById(R.id.customDialog));
//		
//		//创建对话框
//		new AlertDialog.Builder(context)
//		.setTitle("提问")//设置对话框标题
//		.setView(customLayout)//为对话框添加组件
//		.setPositiveButton("提交", new DialogInterface.OnClickListener(){
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				//获取自定义布局上的输入框的值
//				EditText customDialogUserName = (EditText)customLayout.findViewById(R.id.dialogQuestion);
//				Toast.makeText(context, "姓名="+customDialogUserName.getText().toString(), Toast.LENGTH_SHORT).show();
//				addQuestion(customDialogUserName.getText().toString());
//			}
//		})//设置对话框[肯定]按钮
//		.setNegativeButton("取消", null)//设置对话框[否定]按钮
//		.show();
//	}
	
	private void addQuestion(String question)
	{
		PersonQuestion pquestion = new PersonQuestion();
		pquestion.setDoctorID("");
		pquestion.setPersonID(m_personid);
		pquestion.setQuestion(question);
		pquestion.setQuestionTime(String.valueOf(System.currentTimeMillis()));
		try {
			getHelper(this).getQuestionsDao().create(pquestion);
		
			questionListRefresh();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		BasicCommCallback bcc = new BasicCommCallback();
		PersonQuestionsUploadTask task = new PersonQuestionsUploadTask(this,bcc,
				m_personid,"",question,pquestion.getQuestionTime());
		
		HealthThreadPool.getInstance().execute(task);
	}
}
